package com.csdware.devilsalarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class Activity_AlarmCountdown extends AppCompatActivity {
    Application_Data applicationData;

    private Calendar calendar;

    private float TotalSecondLeft;
    private long RefreshTotalSecondLeftTimestamp;
    private final Handler PeriodicUpdateTimeLeftHandler = new Handler();
    private Runnable PeriodicUpdateTimeLeftFunction;

    private TextView DisplayAlarmETAHour;
    private TextView DisplayAlarmETAMinute;
    private TextView DisplayAlarmETASecond;

    AlarmManager alarmManager;
    PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        applicationData = (Application_Data) getApplicationContext();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);  // 使画面延伸到状态栏和导航栏，沉浸感更强
        if (android.os.Build.VERSION.SDK_INT >= 30) {
            WindowInsetsController windowInsetsController = getWindow().getInsetsController();
            if (windowInsetsController != null) {
                windowInsetsController.hide(WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
                windowInsetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
            }
        }
        setContentView(R.layout.activity_alarm_countdown);

        DisplayAlarmETAHour = findViewById(R.id.dsp_alarm_eta_hour);
        DisplayAlarmETAMinute = findViewById(R.id.dsp_alarm_eta_minute);
        DisplayAlarmETASecond = findViewById(R.id.dsp_alarm_eta_second);

        calendar = Calendar.getInstance();
        getAlarmEtaSecondsLeft();

        Intent AlarmIntent = new Intent(this, Receiver_AlarmTimeUp.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, AlarmIntent, PendingIntent.FLAG_IMMUTABLE);
        long triggerTime = System.currentTimeMillis() + (long) (TotalSecondLeft * 1000 - 1000); // 5秒后触发，你可以根据需要修改时间
        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (alarmManager.canScheduleExactAlarms()) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            } else {
                Toast.makeText(getApplicationContext(), R.string.no_background_permission_no_alarm, Toast.LENGTH_SHORT).show();
            }
        } else {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
        }

        PeriodicUpdateTimeLeftFunction = new Runnable() {
            @Override
            public void run() {
                RefreshTimeLeft();
                PeriodicUpdateTimeLeftHandler.postDelayed(this, 100);
            }
        };
    }

    private void getAlarmEtaSecondsLeft() {  // 计算当前时间与闹钟设定时间之间差了多久，也就是还有多久启动闹钟
        RefreshTotalSecondLeftTimestamp = System.currentTimeMillis();
        int NowHour = calendar.get(Calendar.HOUR_OF_DAY);
        int NowMinute = calendar.get(Calendar.MINUTE);
        int NowSecond = calendar.get(Calendar.SECOND);
        int NowMilliSecond = calendar.get(Calendar.MILLISECOND);
        if (NowHour == applicationData.TargetAlarmHour && NowMinute == applicationData.TargetAlarmMinute) {
            TotalSecondLeft = 1.0f;
            return;
        }
        float NowSecondSum = (float) NowHour * 3600.0f + (float) NowMinute * 60.0f + (float) NowSecond + (float) NowMilliSecond / 1000.0f;
        float TargetSecondSum = (float) applicationData.TargetAlarmHour * 3600.0f + (float) applicationData.TargetAlarmMinute * 60.0f;
        if (TargetSecondSum > NowSecondSum) {  // 今天
            TotalSecondLeft = TargetSecondSum - NowSecondSum;
        } else {  // 明天
            TotalSecondLeft = 24.0f * 3600.0f - (NowSecondSum - TargetSecondSum);
        }
    }

    private void RefreshTimeLeft() {
        float RealTotalSecondLeft = TotalSecondLeft - (float) (System.currentTimeMillis() - RefreshTotalSecondLeftTimestamp) / 1000.0f;
        int DisplayedHourLeft = (int) RealTotalSecondLeft / 3600;
        int DisplayedMinuteLeft = ((int) RealTotalSecondLeft % 3600) / 60;
        int DisplayedSecondLeft = ((int) RealTotalSecondLeft % 3600) % 60;
        if (DisplayedHourLeft < 0) DisplayedHourLeft = 0;
        if (DisplayedMinuteLeft < 0) DisplayedMinuteLeft = 0;
        if (DisplayedSecondLeft < 0) DisplayedSecondLeft = 0;
        String DisplayedHourLeftStr;
        String DisplayedMinuteLeftStr;
        String DisplayedSecondLeftStr;
        if (DisplayedHourLeft < 10) DisplayedHourLeftStr = "0" + DisplayedHourLeft;
        else DisplayedHourLeftStr = String.valueOf(DisplayedHourLeft);
        if (DisplayedMinuteLeft < 10) DisplayedMinuteLeftStr = "0" + DisplayedMinuteLeft;
        else DisplayedMinuteLeftStr = String.valueOf(DisplayedMinuteLeft);
        if (DisplayedSecondLeft < 10) DisplayedSecondLeftStr = "0" + DisplayedSecondLeft;
        else DisplayedSecondLeftStr = String.valueOf(DisplayedSecondLeft);
        DisplayAlarmETAHour.setText(DisplayedHourLeftStr);
        DisplayAlarmETAMinute.setText(DisplayedMinuteLeftStr);
        DisplayAlarmETASecond.setText(DisplayedSecondLeftStr);
    }

    @Override
    protected void onPause() {
        super.onPause();
        PeriodicUpdateTimeLeftHandler.removeCallbacks(PeriodicUpdateTimeLeftFunction);  // 如果因为某些bug在任务队列里添加了多个并行的延时任务，removeCallbacks也能将它们一次全部清除
    }

    @Override
    protected void onResume() {
        super.onResume();
        PeriodicUpdateTimeLeftHandler.postDelayed(PeriodicUpdateTimeLeftFunction, 0);
    }


    @Override
    protected void onDestroy() {
        alarmManager.cancel(pendingIntent);
        super.onDestroy();
    }
}
